#重定义系统类
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from itsdangerous import BadData

from apps.oauth import constants
from .models import User


def get_user_by_username(username):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', username):
            # 手机号登录
            user = User.objects.get(mobile=username)
        else:
            # 用户名登录
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    # try:
    #     user = User.objects.get(mobile=account) or User.objects.get(username=account)
    #
    # except User.DoesNotExist:
    #     return None

    #返回user
    return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号
        user = get_user_by_username(username)
        # 校验user是否存在并校验密码是否正确
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
#对邮箱加密
def generic_verify_email_url(user_id):
    # 密匙和有效期
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    data = {'user_id': user_id}
    #加密
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url



#对邮箱tokon解密
def check_verify_email_token(token):
    """
    验证token并提取user
    :param token: 用户信息签名后的结果
    :return: user, None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    try:
        result = serializer.loads(token)
    except BadData:
        return None
    # 3.返回数据
    return result.get('user_id')